package org.system.core.service.system;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.system.core.domain.entity.SysDictData;
import org.system.core.exception.ServiceException;
import org.system.core.mapper.system.SysDictDataMapper;
import org.system.core.utils.MessageUtils;
import org.system.core.utils.SecurityUtils;
import org.system.core.utils.StringUtils;
import org.system.core.utils.dict.DictUtils;

import java.util.List;

/**
 * @author baoRoot
 */
@Service
public class SysDictDataService {

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    public List<SysDictData> selectDictDataList(SysDictData dictData) {
        return sysDictDataMapper.selectDictDataList(dictData);
    }

    public SysDictData selectDictDataById(Long dictCode) {
        return sysDictDataMapper.selectDictDataById(dictCode);
    }

    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        dictDatas = sysDictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    public void insertDictData(SysDictData data) {
        data.setCreateBy(SecurityUtils.getUsername());
        if (sysDictDataMapper.insertDictData(data) <= 0) {
            throw new ServiceException(MessageUtils.message("system.monitor.add_error"));
        }
        List<SysDictData> dictDatas = sysDictDataMapper.selectDictDataByType(data.getDictType());
        DictUtils.setDictCache(data.getDictType(), dictDatas);
    }

    public void updateDictData(SysDictData data) {
        data.setUpdateBy(SecurityUtils.getUsername());
        if (sysDictDataMapper.updateDictData(data) <= 0) {
            throw new ServiceException(MessageUtils.message("system.monitor.update_error"));
        }
        List<SysDictData> dictDatas = sysDictDataMapper.selectDictDataByType(data.getDictType());
        DictUtils.setDictCache(data.getDictType(), dictDatas);
    }

    public void deleteDictDataByIds(Long[] dictCodes) {
        for (Long dictCode : dictCodes) {
            SysDictData data = selectDictDataById(dictCode);
            sysDictDataMapper.deleteDictDataById(dictCode);
            List<SysDictData> dictDatas = sysDictDataMapper.selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
    }

}
